<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:300px"> 
        <InputBox :title="'提还箱城市'" :inputVal1="param.carryCityId" :inputVal2="param.returnCityId" :inputBoxConfig="inputBoxConfig"  @inputChange="inputChange"></InputBox>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>编号</div>
        <el-input v-model="param.releaseNo" clearable placeholder="请输入编号"/>
      </el-form-item>
      <el-form-item style="width:360px">
        <div>创建日期</div>
        <el-date-picker v-model="param.createDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReSet" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">搜索</el-button>
      </el-form-item>
    </el-form>

    <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-button :icon="Delete" type="danger" size="small" round @click="isDelete($event, 'pitch')"
        plain>批量删除</el-button>
      <el-button :icon="Upload" type="primary" size="small" round @click="boxPublish($event, 'pitch')"
        plain>批量上架</el-button>
      <el-button :icon="Download" type="info" size="small" round @click="boxDown($event, 'pitch')"
        plain>批量下架</el-button>
      <el-button :icon="Promotion" type="success" size="small" round @click="activEdite({})" plain>发布</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" @pageChange="onTablePageChange" @activEdite="activEdite" @showInfo="showInfo" @boxPublish="boxPublish" :disableHeaderCheckbox="false" @boxDown="boxDown" @isDelete="isDelete"></Table>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="activDelete">是的</el-button>
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { getAgentSelfPage, agentSubmit, agentTobeReleased, statusCount, downPitch, deletePitch, publishPitch, getBoxNum, getBoxInfo, } from '@/api/boxRent'
// import { getAgentSelfTable, getBoxEastAgentTable, statusCountRent, offShelf, onShelf, deletePitch } from '@/api/boxCallBack'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import {
  Plus,
  Delete,
  Promotion,
  Edit,
  Message,
  Download,
  Upload
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import InputBox from '@/components/inputBox'

const param = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出租中', 10: '仓库中', 15: '待发布' },
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  returnCityId: null,
  carryCityId: null,
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  releaseNo:""
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'releaseNo', colWidth: '150', title: '编号', type: '<change>', command: 'showInfo', isCheck: true },
    { key: 'id', colWidth: '420', title: '提箱/还箱城市', type: 'city', isCheck: true },
    { key: 'boxUsagePeriod', colWidth: '120', title: '箱使用期', type: 'add', after: '天', isCheck: true },
    { key: 'minUnitPrice', colWidth: '120', title: '求租价格', type: 'add', before: '￥',currency:"minUnitPriceCurrency", isCheck: true },
    { key: 'totalInventoryQty', colWidth: '120', title: '求租箱量', type: 'add', after: '个', isCheck: true },
    { key: 'status', colWidth: '120', title: '发布状态', type: 'filter', filter: param.stateFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'createTime', colWidth: '300', title: '创建日期', sortable: true, type: 'dateTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '250',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '编辑',
          // icon: 'Edit',
          command: 'activEdite',
          name:'编辑',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '下架',
          // icon: 'Download',
          command: 'boxDown',
          name:'下架',
          isShow: (row: { status: string; }) => {
            return row.status == '5';
          },
        },
        {
          // content: '上架',
          // icon: 'Upload',
          command: 'boxPublish',
          name: '上架',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '删除',
          // icon: 'Delete',
          command: 'isDelete',
          name:"删除",
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

onActivated(() => {
  getTableData()
});

const startCityId = (id: string) => {
  param.carryCityId = id
}
const backCityId = (id: string) => {
  param.returnCityId = id
}

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    carryCityId: param.carryCityId,
    returnCityId: param.returnCityId,
    beginTotalRentQty: param.beginTotalRentQty - 0 || "",
    endTotalRentQty: param.endTotalRentQty - 0 || "",
    status: param.status,
    releaseNo:param.releaseNo?.trim()
  };
  if (param.createDate) {
    data.beginCreateTime = param.createDate[0];
    data.endCreateTime = param.createDate[1];
  }
  table.config.loading = true;
  // 列表
  getAgentSelfPage(data).then((res: any) => {
    const list = JSON.parse(JSON.stringify(res.data.list));
    formatCityInfo(list)
    table.data = list
    table.config.total = res.data.total;
  });
  //汇总
  data.rentSource = 10 // 租箱来源: 5 - 集装箱公司发布 10 - 货代发布
  statusCount(data).then((res: { data: any }) => {
    const resList = res.data // [ { status: 5, totalQty: 0 },{ status: 10, totalQty: 0 },{ status: 15, totalQty: 0 } ]
    const list = [{ id: 0, name: '全部', num: 0 }, { id: 5, name: '求租中', num: 0 }, { id: 10, name: '仓库中', num: 0 }, { id: 15, name: '待发布', num: 0 }]
    param.typeList = formatStateCount(list, resList)
    table.config.loading = false;
  })
  table.config.loading = false;
}
//重置
function handleReSet() {
  param.carryCityId = null
  param.returnCityId = null
  param.beginTotalRentQty = null
  param.endTotalRentQty = null
  param.createDate = null
  param.releaseNo = ""
  getTableData()
}

//编辑
const router = useRouter();
const activEdite = (row: any) => {
  if(Object.keys(row).length != 0){
    if (row) {
      orderInfo().setRowData(row)
      router.push({
        path:'publishSeekRent',
        query:{
          secondaryEditing: "true"
        } // 是否是下架中编辑
      })
    }
  }else{
    orderInfo().setRowData({})
    router.push('publishSeekRent')
  }
  
  
};
//详情
const showInfo = (row: any) => {
  row.isInfo=true
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push('publishSeekRent')
};
//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
const boxPublish = (row: { id: any }, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要上架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  publishPitch(ids).then(() => {
    getTableData()
  })
};
const boxDown = (row: any, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要下架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  downPitch(ids).then((res: any) => {
    getTableData()
  })
};

//删除 
let deleteList = ref([])
const isDelete = (row: any, opr: any) => {
  if (opr == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要删除的订单')
    }
    deleteList.value = selection.value
  } else {
    deleteList.value = [row.id]
  }
  param.dialogVisible = true;
};
const activDelete = () => {
  let ids = [...deleteList.value]
  deletePitch(ids).then((res: any) => {
    getTableData()
  })
  param.dialogVisible = false;
};


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


onMounted(() => {
  getTableData()

})




// 功能函数
const formatStateCount = (stateList: any, resList: any) => {
  let total = 0;
  stateList.forEach(item => {
    resList.forEach((obj: { status: number; totalQty: number }) => {
      if (item.id == obj.status) {
        item.num = obj.totalQty
        total += obj.totalQty
      }
    })
  })
  stateList.map(obj => {
    if (obj.id == 0) {
      obj.num = total
    }
  })
  return stateList
};

const formatCityInfo = (list: any) => {
  list.forEach((item: any) => {
    // 图片
    let mainFileList = JSON.parse(item.mainFileList);
    if(Object.keys(mainFileList).length == 0){
      item.imgUrl = ''
    }else{
      // item.imgUrl = Object.values(mainFileList).forEach(value => {
      //   return item.url
      // })
      item.imgUrl = mainFileList.map((item: any) => {
        return item.url
      })[0];
    }
  })
}

//修改提还箱城市
const inputChange = (val1,val2) => {
  param.carryCityId = val1 // 提箱城市
  param.returnCityId = val2 //还箱城市
}
const inputBoxConfig = reactive({
  placeholder1:"请输入提箱城市",
  placeholder2:"请输入还箱城市",
})
</script>
<style lang="scss" scoped>
.input-container {
    display: flex;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 5px;
    :deep(.el-input__wrapper) {
      box-shadow: none !important;
      height: 30px;
      // border-radius: 0;
  }
}

</style>
